<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
  import echarts from "echarts";
  require("echarts/theme/macarons"); // echarts theme
  import resize from "./mixins/resize";

  export default {
    mixins: [resize],
    props: {
      className: {
        type: String,
        default: "chart"
      },
      width: {
        type: String,
        default: "100%"
      },
      height: {
        type: String,
        default: "600px"
      },
      chartData: {
        type: Object,
        required: true
      },
      titleInfo: {
        type: Object,
        required: true
      }
    },
    data() {
      return {
        chart: null
      };
    },
    watch: {
      chartData: {
        deep: true,
        handler(val) {
          this.setOptions(val);
        }
      }
    },
    mounted() {
      this.$nextTick(() => {
        this.initChart();
      });
    },
    beforeDestroy() {
      if (!this.chart) {
        return;
      }
      this.chart.dispose();
      this.chart = null;
    },
    methods: {
      getRandomColor() {
        const r = Math.floor(Math.random() * 255);
        const g = Math.floor(Math.random() * 255);
        const b = Math.floor(Math.random() * 255);
        return "rgba(" + r + "," + g + "," + b + ",1)";
      },
      initChart() {
        this.setOptions(this.chartData);
      },
      setOptions(chartData) {
        this.chart = echarts.init(this.$el, "macarons");
        const titleInfo = this.titleInfo;
        this.chart.setOption({
          color: ["#3398DB"],
          title: {
            text: titleInfo.text,
            subtext: titleInfo.subtext
          },
          tooltip : {
            trigger: 'axis',
            axisPointer : {
              type : 'shadow'
            }
          },
          grid: {
            left: '1%',
            right: '1%',
            bottom: '1%',
            containLabel: true
          },
          xAxis: {
            type : 'category',
            data: chartData.xTitle,
            axisTick: {
              alignWithLabel: true
            }
          },
          yAxis: {},
          series: [{
            name: chartData.name,
            type: 'bar',
            barWidth: '60%',
            data: chartData.series,
            label: {
              normal: {
                show: true,
                position: 'inside'
              }
            }
          }]
        });
      }
    }
  };
</script>
